package com.tigerhhzz.service.impl;

import com.tigerhhzz.domain.LoginUser;
import com.tigerhhzz.domain.ResponseResult;
import com.tigerhhzz.domain.User;
import com.tigerhhzz.service.LoginService;
import com.tigerhhzz.utils.JwtUtil;
import com.tigerhhzz.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author tigerhhzz
 * @date 2022/5/27 15:14
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {

        //1,使用springsecurtiy中AuthenticationManager进行用户认证
           //把用户名和密码封装成UsernamePasswordAuthenticationToken对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
            //让autenticationmanagere中的autenticate方法 帮助我们进行认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //2,如果认证失败，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }

        //3,如果认证成功，使用userid生成一个jwt令牌   jwt存入ResponseResult中 返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getId().toString();

        String jwt = JwtUtil.createJWT(userid);

        //4,userid作为key，把完整的用户信息存入redis中
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userid,loginUser);
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);

        return new ResponseResult(200,"登陆成功",map);

    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        //删除redis中的值
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200,"退出成功");
    }

}
